<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="题目">
          <el-input v-model="searchInfo.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="题目" prop="title" width="320" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="类型" show-overflow-tooltip>
          <template #default="scope">
              {{ getType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="章节" show-overflow-tooltip>
          <template #default="scope">
              {{ getChapter(scope.row.chapter) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="无人机类型" show-overflow-tooltip>
          <template #default="scope">
              {{ getDroneType(scope.row.droneType) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="执照类型" show-overflow-tooltip>
          <template #default="scope">
              {{ getIdType(scope.row.idType) }}
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="80">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="userForm" label-width="100" :model="form" :rules="rules">
        <el-form-item label="题目" prop="title">
          <el-input v-model="form.title" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model.number="form.type" class="ml-4">
            <el-radio :value="1" size="large">单选题</el-radio>
            <el-radio :value="2" size="large">判断题</el-radio>
            <el-radio :value="3" size="large">多选题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="章节" prop="chapter">
          <el-select v-model="form.chapter" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in zjData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="无人机类型" prop="droneType">
          <el-select v-model="form.droneType" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选项" style="align-items: normal;" prop="options">
          <div v-for="(item, index) in form.option" style="display: flex;align-items: center;margin-bottom: 10px;">
            <span>{{ letters[index] }}</span>
            <el-input v-model="item.name" placeholder="请输入" style="width: 480px;margin-left: 10px;" />
            <el-icon :size="30" color="#3b82f6" style="cursor: pointer;margin-left: 8px;">
              <CirclePlus v-if="index == 0" @click="addTime(index)" />
              <Remove v-else @click="delTime(index)" />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="执照类型" prop="idType">
          <el-select v-model="form.idType" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in idTypeData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="答案" prop="answers">
          <el-select v-if="form.type==3" v-model="form.answers" multiple placeholder="请选择" style="width: 500px">
            <el-option v-for="item in answers" :key="item" :label="item" :value="item" />
          </el-select>
          <el-select v-else v-model="form.answers" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in answers" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="解析" prop="analysis" style="align-items: normal;">
          <el-input v-model="form.analysis" placeholder="请输入" type="textarea" :rows="5" style="width: 500px;" />
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  questionList,
  questionAdd,
  questionEdit,
  questionDelete
} from '@/api/tiku'

import { useUserStore } from '@/pinia/modules/user'
import { reactive, ref, onMounted,computed } from 'vue'
import { useAppStore } from "@/pinia";
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomPic from '@/components/customPic/index.vue'
defineOptions({
  name: 'User'
})
const appStore = useAppStore()
const defaultProps = {
  children: 'children',
  label: 'name',
}

const userStore = useUserStore()

const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'

const form = ref({
  title: '',
  chapter: '',
  droneType: '',
  options: [],
  option: [{ name: '' }],
  type: 1,
  title: '',
  answer: [],
  answers:[],
  idType: '',
  analysis:''
})
const letters = ref(['A','B','C','D','E','F'])
const answers = computed(()=>{
  return letters.value.slice(0,form.value.option.length)
})
const zjData = ref([
{
    name: '所有',
    id: 0
  },
  {
    name: '概述',
    id: 1
  },
  {
    name: '空域',
    id: 2
  },
  {
    name: '法律法规',
    id: 3
  },
  {
    name: '系统组成',
    id: 4
  },
  {
    name: '任务规划',
    id: 5
  },
])
const typeData = ref([
{
    name: '所有',
    id: 0
  },
  {
    name: '多旋翼无人机',
    id: 1
  },
  {
    name: '固定翼无人机',
    id: 2
  },
  {
    name: '垂直起降无人机',
    id: 3
  },
  {
    name: '无人直升机',
    id: 4
  },
])
const idTypeData = ref([
{
    name: '所有',
    id: 0
  },
  {
    name: '视距内驾驶员',
    id: 1
  },
  {
    name: '超视距驾驶员',
    id: 2
  },
  {
    name: '无人机教员',
    id: 3
  }
])
let validate1 = (rule, value, callback) => {
  let flag = form.value.option.some(item=>!item.name)
  if (flag) {
    callback(new Error('请输入选项'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: [{ required: true, message: '请输入题目', trigger: 'blur' }],
  droneType: [{ required: true, message: '请选择无人机类型', trigger: 'change' }],
  idType: [{ required: true, message: '请选择执照类型', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  chapter: [{ required: true, message: '请选择章节', trigger: 'change' }],
  answers: [{ required: true, message: '请选择答案', trigger: 'change' }],
  options: [{ required: true, validator: validate1, trigger: 'change' }],
})
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
const userForm = ref(null)

const searchInfo = ref({
  title: ''
})
const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  page.value = 1
  searchInfo.value = {
    title: ''
  }
  getTableData()
}
const initForm = () => {
  userForm.value.resetFields()
  form.value = {
    title: '',
  chapter: '',
  droneType: '',
  options: [],
  option: [{ name: '' }],
  type: 1,
  title: '',
  answer: [],
  answers:[],
  idType: '',
  analysis:''
  }
}
function getType(val){
  const arr = ['','单选题','判断题','多选题']
  return arr[val]
}
function getChapter(val){
  return zjData.value.find(item=>item.id==val)?.name||'所有'
}
function getDroneType(val){
  return typeData.value.find(item=>item.id==val)?.name||'所有'
}
function getIdType(val){
  return idTypeData.value.find(item=>item.id==val)?.name||'所有'
}
const isEdit = ref(false)
const dialogTitle = ref('新增')
const addUnit = () => {
  dialogTitle.value = '新增'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const handleClose = (done) => {
  initForm()
  done()
}

const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await questionList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()

onMounted(() => {

})
function addTime(index) {
  form.value.option.push({
    name: ''
  })
  form.value.answers=[]
}
function delTime(index) {
  form.value.option.splice(index, 1)
  form.value.answers=[]
}

const enterDialog = async () => {
  console.log(form.value, 'form'); 
  userForm.value.validate(async (valid) => {
    if (valid) {
      //form.value.options = form.value.option.map(item=>item.name)
      form.value.options = form.value.option.map((item,index)=>{
        return letters.value[index]+' '+ item.name
      })
      form.value.answer = form.value.type==3? form.value.answers:[form.value.answers]
      let res
      if (isEdit.value) {
        res = await questionEdit(form.value)
      } else {
        res = await questionAdd(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await questionDelete(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑'
  form.value = JSON.parse(JSON.stringify(row))
  console.log(JSON.parse(form.value.options),'vvv')

  form.value.option = JSON.parse(form.value.options).map(item=>{
    return {
      name:item.split(' ')[1]
    }
  })
  form.value.answers = form.value.type==3?JSON.parse(form.value.answer):JSON.parse(form.value.answer)[0]
  form.value.questionId = form.value.id
  dialogFormVisible.value = true
}

const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  form.value.headerImg = ''
}
const uploadSuccess = (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'warning',
      message: res.message
    })
    fileList.value.pop()
    return
  }
  form.value.headerImg = res.result
}

</script>

<style lang="scss">
.el-upload-list--picture-card {
  display: flex;
  flex-wrap: nowrap;
}

.el-upload-list__item {
  justify-content: center;
}
</style>

